package com.hhu.wangzb.shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhu.wangzb.common.dao.UserDao;
import com.hhu.wangzb.common.dao.UserPermissionDao;
import com.hhu.wangzb.common.dao.UserProjectDao;
import com.hhu.wangzb.common.entity.UserEntity;
import com.hhu.wangzb.common.entity.UserPermissionEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public class AccountRealm extends AuthorizingRealm {

    @Autowired(required = false)
    UserDao userDao;

    @Autowired(required = false)
    UserPermissionDao userPermissionDao;

    @Autowired(required = false)
    UserProjectDao userProjectDao;

    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 用户名
        String username = (String) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 获取用户权限信息
        info.addStringPermissions(getUserPermissions(username));

        return info;
    }

    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {

        SimpleAuthenticationInfo info = null;

        if (token instanceof UsernamePasswordToken) {
            UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
            // 密码校验的工作交给service层，这里直接放行，只起到保存认证信息的作用
            info = new SimpleAuthenticationInfo(usernamePasswordToken.getUsername(),
                    usernamePasswordToken.getPassword(), this.getName());
        }

        return info;
    }


    /**
     * 获取用户权限字符串集合
     * @param principal 用户身份标识（用户名）
     * @return 用户权限字符串集合
     */
    private List<String> getUserPermissions(String principal) {

        Integer userId = queryUserId(principal);

        // 查询用户权限信息
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("u_id", userId);

        QueryWrapper<UserPermissionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap).select("permission");

        List<UserPermissionEntity> userPermissionEntities = userPermissionDao.selectList(queryWrapper);

        List<String> results = new ArrayList<>();

        for (UserPermissionEntity entity : userPermissionEntities) {
            results.add(entity.getPermission());
        }

        return results;
    }

    /**
     * 根据用户身份标记查询用户id
     * @param principal 户身份标记（用户名）
     * @return 用户数据id
     */
    private Integer queryUserId(String principal) {
        // 查询用户信息
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("username", principal);

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap).select("id");

        UserEntity userEntity = userDao.selectOne(queryWrapper);

        return userEntity.getId();
    }
}
